package com.xb.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xb.constant.SearchConstant;
import com.xb.page.PageBean;
import com.xb.service.SearchService;
import com.xb.vo.CourseVO;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class SearchServiceImpl implements SearchService {

    @Resource
    private RestHighLevelClient client;

    @Override
    public PageBean<CourseVO> searchCourcesByName(String courseName, Integer pageNum, Integer pageSize) {
        PageBean<CourseVO> page = new PageBean<>();
        List<CourseVO> list = new ArrayList<>();
        page.setPageCount(pageSize);
        page.setList(list);
        page.setPageNumber(pageNum);
        page.setTotalCount(getSearchTotal(courseName));
        SearchRequest searchRequest = new SearchRequest(SearchConstant.ES_INDEX);
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //设置分页条件的
        builder.from(page.getStartIndex());
        builder.size(pageSize);
        //进行搜索条件的设置
        builder.query(xbBoolQuery(courseName));//把条件抽取出来了
        //高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font color='red'>");
        highlightBuilder.postTags("</font>");
        builder.highlighter(highlightBuilder);
//        builder.minScore(1);//最低分数
        searchRequest.source(builder);
        SearchResponse response = null;
        try {
            response = client.search(searchRequest,
                    RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());
        System.out.println(response.getTook());
        for (SearchHit hit : hits) {
            CourseVO item = JSONObject.parseObject(hit.getSourceAsString(), CourseVO.class);
            HighlightField highlightField = hit.getHighlightFields().get("title");
            Text[] fragments = highlightField.getFragments();
            item.setTitle(fragments[0].toString());//将高亮的字段放入 取代原来的
            list.add(item);
        }

        return page;
    }

    //根据课程名搜索的条件的抽取
    public BoolQueryBuilder xbBoolQuery(String title){
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.should(QueryBuilders.matchQuery("title", title));
        boolQuery.should(QueryBuilders.matchQuery("introduce", title));
        return boolQuery;
    }
    public Long getSearchTotal(String title) {
        SearchRequest searchRequest = new SearchRequest(SearchConstant.ES_INDEX);
        SearchSourceBuilder builder = new SearchSourceBuilder();
//        builder.minScore(1);//最低分数
        builder.query(xbBoolQuery(title));//match条件查询
        searchRequest.source(builder);
        SearchResponse response = null;
        try {
            response = client.search(searchRequest,
                    RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SearchHits hits = response.getHits();
        return hits.getTotalHits().value;
    }


    @Override
    public List<CourseVO> searchCourcesByLabel(String label) {
        List<CourseVO> list = new ArrayList<>();
        SearchRequest searchRequest = new SearchRequest(SearchConstant.ES_INDEX);
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //进行搜索条件的设置
        builder.query(xbLabelBoolQuery(label));//把条件抽取出来了
        searchRequest.source(builder);
        SearchResponse response = null;
        try {
            response = client.search(searchRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());
        System.out.println(response.getTook());
        for (SearchHit hit : hits) {
            CourseVO item = JSONObject.parseObject(hit.getSourceAsString(), CourseVO.class);
            list.add(item);
        }
        return list;

    }
    //根据课程标签搜索的条件的抽取
    public BoolQueryBuilder xbLabelBoolQuery(String title){
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.should(QueryBuilders.termQuery("label1", title));
        boolQuery.should(QueryBuilders.termQuery("label2", title));
        boolQuery.should(QueryBuilders.termQuery("label3", title));
        return boolQuery;
    }
}
